package com.kfm.jdbc;

import java.sql.*;

public class JdbcDemo {

    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
//加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
//通过驱动管理类获取数据库链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis",
                            "root","");
//定义sql语句
            String sql = "select * from userinfo where username = ?";
//获取预处理statement
            preparedStatement = connection.prepareStatement(sql);
//为占位符赋值
            preparedStatement.setString(1, "李四");
//向数据库发出sql语句，获取查询结果集
            rs =preparedStatement.executeQuery();
//遍历查询结果集
            while(rs.next()){
                System.out.println(rs.getString("id"));
                System.out.println(rs.getString("username"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
//释放资源
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(preparedStatement!=null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


